import LazyLoader from "@/components/lazy_loader";
import { lazy } from "react";
import { IRoute } from "./router.types";
import { deepClone } from "@/utils";
import { setCache } from "@/utils/storage";
import { MenuTypes } from "@/views/system/menu/dictionary";
//按钮权限
let buttonPermissions: string[] = [];

//处理路由数据
export const dealRouteData = (permissionBox: Array<IRoute>) => {
    buttonPermissions = [];
    //权限信息统一处理
    let result = dealUserPermission(permissionBox);
    //处理菜单显示权限
    let menuRouter = filterAsyncRouters(result);
    //菜单显示权限
    let menuPermissions = dealShowMenus(menuRouter);
    //处理用户可进入路由权限
    let paveRouters = paveAsyncRouters(menuRouter);
    let homeRoute = paveRouters[0];
    homeRoute.element = loadComponent(homeRoute.path, homeRoute.menuType);
    setCache('home', homeRoute);
    return {
        buttonPermissions,
        paveRouters,
        menuRouter: menuPermissions,
        homeRoute
    }
}
//处理用户权限菜单中的权限信息
export const dealUserPermission = (permissions: Array<IRoute>) => {
    if (!permissions || !permissions.length) return [];
    permissions.map((item: IRoute) => {
        item.name = item.name;
        item.meta = {
            title: item.name,
            icon: item.icon
        };
        //如果是目录的处理
        if (item.menuType == MenuTypes.Catalog) {
            try {
                let firstItem = item?.children?.[0];
                if (firstItem?.menuType == MenuTypes.Catalog) {
                    item.redirect = item.path + '/random'
                } else {
                    let res = getMenuFirst(item);
                    item.redirect = res.path || '/';
                }
            } catch {
                item.redirect = item.path + '/random'
            }
        }
        //如果有子集，需要递归处理
        if (item.children?.length) {
            item.children = dealUserPermission(item.children);
        } else {
            item.children = null;
        }
        //如果是按钮权限
        if (item.menuType == MenuTypes.Button) {
            buttonPermissions.push(item.path);
        }
        //如果是菜单权限
        if (item.menuType == MenuTypes.Menu) {
            //检查菜单下是否有其他菜单权限
            if (hasChildren(item)) {
                item.children = null;
            } else {
                item.children = item?.children?.filter((child: IRoute) => child.menuType == MenuTypes.Menu);
            }
            item.hidden = item.visible == '1' ? false : true;
        }
    });
    return permissions;
}
//获取目录菜单里的第一项
export const getMenuFirst = (item: IRoute): any => {
    if (!item) return {};
    //如果是菜单 直接返回
    if (item.menuType == MenuTypes.Menu) {
        return item;
    }
    //如果是目录 继续下探
    if (item.menuType == MenuTypes.Catalog) {
        let getItem = item.children?.find((menu: IRoute) => menu.menuType == MenuTypes.Menu);
        if (getItem) {
            return getMenuFirst(getItem)
        } else {
            return item;
        }
    }
}
//路由菜单转换
export const filterAsyncRouters = (routerMap: IRoute[]) => {
    const accessRouters: IRoute[] = [];
    routerMap.map((item: IRoute) => {
        item.meta = item.meta || {};
        let { path, name, menuType, visible, meta, redirect, children } = item;
        let isHidden = visible == '1' ? false : true;
        //路由对象和权限对象
        let route: IRoute = {
            path,
            key: path,
            label: name,
            meta,
            type: menuType,
            redirect,
            hidden: isHidden,
            children: children ? filterAsyncRouters(children) : null,
            element: path,
        }
        accessRouters.push(route);
    })
    return accessRouters
}
//菜单显示权限处理
export const dealShowMenus = (routes: IRoute[]) => {
    let list = deepClone(routes);
    let res = list.filter((item: IRoute) => {
        delete item.menuType;
        if (!item.hidden && item.children) {
            let result = dealShowMenus(item.children);
            item.children = result?.length ? result : null;
        }
        return !item.hidden;
    })
    return res;
}
//路由可进入
export const paveAsyncRouters = (routes: IRoute[], breadcrumb: any = []) => {
    let res: Array<any> = []
    routes.forEach((route: IRoute) => {
        const tmp = deepClone(route)
        if (tmp.children) {
            let childrenBreadcrumb = deepClone(breadcrumb)
            childrenBreadcrumb.push(route)
            let tmpRoute = deepClone(route)
            tmpRoute.meta.breadcrumb = deepClone(childrenBreadcrumb)
            delete tmpRoute.children
            res.push(tmpRoute)
            let childrenRoutes = paveAsyncRouters(tmp.children, childrenBreadcrumb)
            childrenRoutes.map(item => {
                res.push(item)
            })
        } else {
            let tmpBreadcrumb = deepClone(breadcrumb)
            tmpBreadcrumb.push(tmp)
            tmp.meta.breadcrumb = deepClone(tmpBreadcrumb)
            res.push(tmp)
        }
    })
    return res
};

//校验菜单是否有子集不需要显示的菜单（隐藏菜单）
export const hasChildren = (item: IRoute) => {
    return (item?.children) && !item.children.some(item => item.visible == '0');
}

//根据路径加载页面组件
export const loadComponent = (component: string, type: string | undefined) => {
    const modules: any = import.meta.glob('@/views/**/*.tsx', { eager: true });
    //需要加载路由组件
    if (component && type == MenuTypes.Menu) {
        return LazyLoader(lazy(async () => modules[`/src/views${component}.tsx`]));
    }
}